#include "log.h"
#include "media.h"
#include <unistd.h>
#include <stdlib.h>
#include "protocol.h"
#include "server.h"
#include <stdio.h>
#include <string.h>
#include "common.h"
#include <sys/signal.h>

#define UNIX_SOCK_FILE_NAME "/tmp/media_server_sock"

static media_t *g_media = NULL;

void signal_handler(int sig)
{
    log_info("Exit by SIGINT\n");

    media_ffmpeg_delete(g_media);
    socket_server_stop();
    exit(0);
}

int main(int argc, char **argv)
{
    log_info("media server start...\n");

    int ret = 0;
    sig_t sig;

    media_t *media = media_ffmpeg_new();
    if (!media) {
        log_error("protocol register media error\n");
        goto exit1;
    }

    g_media = media;

    ret = protocol_register_media(media);
    if (ret) {
        log_error("protocol register media error\n");
        goto exit2;
    }

    sig = signal(SIGINT, signal_handler);
    if (SIG_ERR == sig) {
        log_error("register signal SIGINT failed\n");
        goto exit2;
    }

    ret = socket_server_start(UNIX_SOCK_FILE_NAME, protocol_msg_handle);
    if (ret != RET_OK) {
        log_error("start socker server failed: %d\n", ret);
        goto exit3;
    }

    while (1) {
        sleep(1);
    }

    exit3:
    socket_server_stop();

    exit2:
    media_ffmpeg_delete(media);
    
    exit1:

    return 0;
}